﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Rhizome.Contract;
using Rhizome.Model.Validation;

namespace Rhizome.Model
{
    public abstract class ActiveItemBase<TPlant> : ItemBase<TPlant>, IValidate
    {
        private IActiveObject _activeObject;

        private IActiveObjectHost ActiveObjectHost
        {
            [DebuggerStepThrough]
			get { return GetValue(ActiveObjectHostProperty); }
        }

        protected abstract IEnumerator Steps();

        public override void Initialize()
        {
            lock (this)
            {
                if (_activeObject != null)
                    throw new InvalidOperationException("ActiveObject is not null before entry");

                _activeObject = new DelegateActiveObject(ActiveObjectHost, Steps()) {Active = true};
            }
        }

        public override void Cleanup()
        {
            lock (this)
            {
                if (_activeObject == null) return;
                _activeObject.Active = false;
                _activeObject = null;
            }
        }

        protected void Sleep(int interval)
        {
            lock (this)
            {
                if (_activeObject != null) 
                    _activeObject.Sleep(interval);
            }
        }

    	#region Implementation of IValidate

    	public virtual IEnumerable<IValidationResult> GetValidationResults()
    	{
			if (ActiveObjectHost == null)
				yield return ValidationResult.ActiveObjectHostIsNull;
    	}

    	#endregion
    }

	public abstract class ActiveItemBase : ActiveItemBase<object> {}
   
}